package com.esun.common.utils;

import java.util.List;

/**
 * SQL语句工具类
 *
 * @author John.xiao
 * @date 2021/3/18 9:13
 */
public class SqlUtils {


	public final static String REGEX = "'|and|exec|execute|insert|select|delete|update|count|drop|\\*|%|chr|mid|master|truncate|" +
			"char|declare|sitename|net user|xp_cmdshell|;|or|-|\\+|,|like'|and|exec|execute|insert|create|drop|" +
			"table|from|grant|use|group_concat|column_name|" +
			"information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|\\*|" +
			"chr|mid|master|truncate|char|declare|or|;|-|--|\\+|,|like|//|/|%|#";

	/**
	 * 把SQL关键字替换为空字符串
	 *
	 * @param param
	 * @return
	 */
	public static String filter(String param) {
		if (param == null) {
			return null;
		}
		// (?i)不区分大小写替换
		return param.replaceAll("(?i)" + REGEX, "");
	}

	/**
	 * 将批量查询参数转成带（）String
	 *
	 * @param list 参数列表
	 * @return 字符串
	 */
	public static String getBatchString(List<String> list) {
		if (list == null || list.size() == 0) {
			return null;
		}
		StringBuilder builder = new StringBuilder();
		for (String s : list) {
			builder.append("'");
			//sql注入过滤
			s = SqlUtils.filter(s);
			builder.append(s);
			builder.append("'");
			builder.append(",");

		}
		builder.setLength(builder.length() - 1);
		return builder.toString();
	}
}
